%% Remote reference processig
% Computes bi-variate transfer functions between two channels, given
% two input & one output channel

% Latest date 18.11.2002

% known bugs
% rr computation - not correct (et149.edi with geotool & rrtranfn difference) 11.11.2002

% bug fixed - correct signs for the cross spectra
% compared with readedi1 erros, z coh found correct
% Hey there is some problem. In rr the autospecs are always complex ? 10.11.2002
% Fixed - compared rr computation with Geotools for et149.edi (7 channel) -ok 18.11.2002
% RR variance (error^2) computation is not yet done
% latest date 31.12.2002  ( New Year Eve)


%zij = za zb - zc zd;
%tf = zxy zyx zxx zyy
function[tf] = rrTransFn(SPM1,ProcDef),

nfreq=ProcDef.nfrq;
EQN=ProcDef.rreqn;
neq=ProcDef.neq;

for i = 1:nfreq,
   SPM(i,:,:) = SPM1.spectra(i).data;
end;

tf = zeros([nfreq neq+2]);

for l = 1:neq,
i = EQN(l,1);
j = EQN(l,2);
k = EQN(l,3);
p = sqrt(-1);
q = EQN(l,4);
r = EQN(l,5);

za = SPM(:,q,j)+p*SPM(:,j,q);  
zg = SPM(:,r,k)+p*SPM(:,k,r);

if i<r,
   zb = SPM(:,r,i)+p*SPM(:,i,r);
elseif i>r,
   zb = SPM(:,i,r)-p*SPM(:,r,i);
end;

if r>j,
   zc = SPM(:,r,j)+p*SPM(:,j,r);
elseif r<j,
   zc = SPM(:,j,r)-p*SPM(:,r,j);
end;

if q>k,
   ze = SPM(:,q,k)+p*SPM(:,k,q);
elseif q<k,
   ze = SPM(:,k,q)-p*SPM(:,q,k);
end;

if i>q,
   zd = SPM(:,i,q)-p*SPM(:,q,i);
elseif i<q,
   zd = SPM(:,q,i)+p*SPM(:,i,q);
end;

den = za.*zg - ze.*zc;
top = [za.*zb-zc.*zd zg.*zd-ze.*zb];

tf(:,l) = (top(:,1)./den);
tf(:,l+2) = (top(:,2)./den);

end;

for i = 1:nfreq,
   data(:,:) = SPM(i,:,:);
   c1 = cohe(tf(i,3),tf(i,1),data,'Ex');
   c2 = cohe(tf(i,2),tf(i,4),data,'Ey');
   dof = SPM1.spectra(i).dof.avgt*SPM1.spectra(i).dof.avgf;
   [tf(i,7),tf(i,5)] = BivError(c1,dof,data,'Ex');
   [tf(i,6),tf(i,8)] = BivError(c2,dof,data,'Ey');
end;

